Introduction to Machine Learning

Unit 17: Gradient Descent for Multiple Regression + Feature Selection

1. Introduction

Building on Unit 16, this unit extends Gradient Descent to the multiple linear regression setting, formalizes the vectorized update rules, and covers two practical essentials: Feature Scaling and Feature Selection. We study two feature selection methods tailored to regression: the Correlation Filter (a model-independent filter) and p-value-based selection (an embedded method that inspects coefficient significance after training).

Learning Objectives

2. Theory

2.1 Notation Recap

SymbolMeaningDimension
\( m \)Number of rows / training examplesscalar
\( p-1 \)Number of raw feature columns; after adding bias column, dimension is \( p \)scalar
\( x_i \)Feature vector for example \( i \) (with \( x_{i,0} = 1 \) for the bias)\( p \times 1 \)
\( y_i \)Target / label for example \( i \)scalar
\( \theta \)Model parameter / weight vector (\( \theta_0 \) is the bias)\( p \times 1 \)
\( \hat{y}_i \)Prediction: \( \hat{y}_i = \theta^T x_i \)scalar
\( \alpha \) (or \( \eta \))Learning rate (step-size hyperparameter)scalar

2.2 Gradient Descent Pseudocode (Generic)

Goal: Minimize the scalar function \( f(\theta) \).

Hyperparameters: Number of epochs \( N \), learning rate \( \eta \).

  1. Pick a random starting point \( p_0 \).
  2. For \( i = 0, \ldots, N-1 \):
    1. Calculate the gradient \( \nabla f(p_i) \).
    2. Set \( p_{i+1} = p_i - \eta \nabla f(p_i) \).
  3. Return \( p_N \) (the converged parameters).

2.3 Gradient Descent for Multiple Variables

For the multi-variable linear hypothesis \( h_\theta(x) = \theta_0 + \theta_1 x_1 + \cdots + \theta_{p-1} x_{p-1} = \theta^T x \) (with \( x_0 = 1 \)) and MSE cost:

\[ J(\theta) = \frac{1}{2m} \sum_{i=1}^{m} \left( \theta^T x_i - y_i \right)^2 \]

Defining the error per example \( e_i = \theta^T x_i - y_i \), we differentiate through the chain rule:

\[ \frac{\partial J}{\partial \theta_j} = \frac{1}{2m} \sum_{i=1}^{m} 2 e_i \frac{\partial e_i}{\partial \theta_j}, \quad \frac{\partial e_i}{\partial \theta_j} = x_{i,j} \]

So the per-parameter gradient is:

\[ \frac{\partial J}{\partial \theta_j} = \frac{1}{m} \sum_{i=1}^{m} \left( \theta^T x_i - y_i \right) x_{i,j} \]

In compact matrix notation, the whole gradient vector becomes:

\[ \nabla J(\theta) = \frac{1}{m} X^T (X\theta - y) \]

And the simultaneous vectorized update:

\[ \theta := \theta - \alpha \nabla J(\theta) \]

2.4 Worked Multi-Variable GD Example

Consider the first row of a 4-column dataset (bias column \( x_0 = 1 \), then 3 real features). Assume all four weights are initialized to \( \theta_0 = \theta_1 = \theta_2 = \theta_3 = 0.59 \), true label \( y = 2 \), and we are processing a batch of size 1 for simplicity.

\( x_0 \)\( x_1 \)\( x_2 \)\( x_3 \)\( \hat{y} = \theta^T x \)\( y \)\( e = \hat{y} - y \)\( \partial J/\partial \theta_0 \)\( \partial J/\partial \theta_1 \)\( \partial J/\partial \theta_2 \)\( \partial J/\partial \theta_3 \)
11.52-1.21.652-0.35-0.35 · 1-0.35 · 1.5-0.35 · 2-0.35 · (-1.2)
Numerical values of the gradients (click to reveal)
\begin{align} \partial J/\partial \theta_0 &= -0.35 \\ \partial J/\partial \theta_1 &= -0.525 \\ \partial J/\partial \theta_2 &= -0.70 \\ \partial J/\partial \theta_3 &= +0.42 \end{align}

With \( \alpha = 0.1 \), the updates would increase \( \theta_0, \theta_1, \theta_2 \) and decrease \( \theta_3 \), nudging \( \hat{y} \) upward toward the target \( y = 2 \).

2.5 The Learning Rate \( \alpha \) — Step Size of Gradient Descent

Gradient descent updates parameters by taking steps proportional to the slope of the cost function. The step size is controlled by the hyperparameter \( \alpha \) (learning rate).

α too small
α well-tuned
α too large

2.6 Why Feature Scaling is Essential

When features have very different scales, gradient descent behaves inefficiently.

Example: House Price Prediction

Without scaling:

Solution: Scale all features to comparable ranges (e.g., 0–1 min-max or standardized z-scores).

2.7 When to Stop Gradient Descent

StrategyHow it Works
Cost-Change Threshold Stop when \( |J(t) - J(t-1)| < \varepsilon \), e.g., \( \varepsilon = 10^{-6} \)
Fixed Iterations Run for a set number of epochs, say 1000 (simplest, but may waste compute or under-converge)
Validation Performance Stop when validation error starts increasing → Early Stopping (prevents overfitting!)
Gradient Magnitude Stop when \( \|\nabla J\| < \varepsilon \) — the gradient itself is nearly zero

2.8 Feature Selection for Regression

Feature selection improves model performance, training speed, and interpretability by discarding irrelevant or redundant features. We focus on two regression-tailored methods.

Method 1: Correlation Filter (Model-Independent)

Earlier we saw Chi-Square, ANOVA, and other filter methods. For regression with a continuous target, the Pearson Correlation Coefficient is the most common filter. It measures the linear relationship between each feature and the target.

\[ r \in [-1,\ +1] \]

Like other filter methods, we can either keep the top-k columns or select columns exceeding a threshold (say \( |r| > 0.3 \)).

Note: Correlation works with one-hot encoded categorical variables, but ANOVA or Mutual Information are more statistically natural choices for purely categorical features.

Method 2: p-value-Based Selection (Embedded Method)

After training a linear regression model, we can examine the statistical significance of each coefficient via its p-value. Formally, we test the null hypothesis:

\[ H_0: \theta_j = 0 \quad \text{("feature } j \text{ has no effect on the target")} \]

Decision rule (typical):

Feature Selection Families (Big Picture)

FamilyHow it WorksExamples
Filter Select features before training, using statistical tests independent of the final model Chi-square, ANOVA, Pearson Correlation, Mutual Information
Wrapper Train the model many times with different subsets to pick the best-performing subset Forward Selection, Backward Elimination, Recursive Feature Elimination (RFE)
Embedded Feature selection happens during / as a byproduct of model training Tree-based feature importances, Lasso (Unit 18!), p-value pruning

3. Interactive Examples

Example 1: Interpret the Matrix Update

Given \( X \in \mathbb{R}^{500 \times 20} \) (with bias column), \( \theta \in \mathbb{R}^{20 \times 1} \), \( y \in \mathbb{R}^{500 \times 1} \).

A. What are the dimensions of the prediction vector \( \hat{y} = X\theta \)?

\( X \) is \( 500 \times 20 \), \( \theta \) is \( 20 \times 1 \).
\[ \hat{y} = X\theta \in \mathbb{R}^{500 \times 1} \]
One prediction per training example. ✓

B. What are the dimensions of the residual \( X\theta - y \) and of the full gradient \( \nabla J(\theta) \)?

Residual \( X\theta - y \): \( 500 \times 1 \) (same as \( \hat{y} \) and \( y \)).
Gradient \( \nabla J = \frac{1}{m} X^T (X\theta - y) \): \( X^T \) is \( 20 \times 500 \), times \( 500 \times 1 \) gives
\[ \nabla J(\theta) \in \mathbb{R}^{20 \times 1} \]
One partial derivative per parameter, as expected. ✓

Example 2: Correlation Filter Reasoning

A dataset of 8 features has Pearson correlations with the target shown below:

FeatureCorrelation (r) with Target
Age+0.04
Income+0.72
Zip-code (one-hot)−0.02
Education-Years+0.31
Height−0.08
Credit Score−0.58
Shoe Size+0.01
Family Size+0.22

Task: Apply the threshold \( |r| > 0.3 \). Which features are kept?

Kept (|r| > 0.3):
  • Income (\( r = +0.72 \)) — strong positive linear relationship
  • Education-Years (\( r = +0.31 \)) — just above threshold, positive
  • Credit Score (\( r = -0.58 \)) — moderate negative linear relationship
Dropped (low linear association): Age, Zip-code, Height, Shoe Size, Family Size (0.22 < 0.3).

Caution: Correlation only captures linear association. A strong non-linear relationship could have r ≈ 0 and would be dropped by this filter.

Example 3: Spot the p-value Interpretation Mistake

A student argues: "Since feature X's p-value is 0.08 (greater than 0.05), we have proven that X has no effect on the target whatsoever."

Mistake: Confusing "failure to reject \( H_0 \)" with "accepting \( H_0 \)." A high p-value is not proof of no effect.

Correct interpretation:

With p = 0.08, the observed data are not sufficiently unlikely under the null hypothesis \( \theta_j = 0 \). So we fail to reject \( H_0 \) at the α = 0.05 level. This does not mean the feature is definitely irrelevant — it might be a weak effect or the sample might be too small to detect it. Use domain knowledge and cross-validated performance before dropping it.

4. Numerical Solutions

Problem 1: Vectorized Gradient on Small Matrix

Mini-batch of 3 examples, 2 real features + bias column (p = 3):

\[ X = \begin{bmatrix} 1 & 1 & 2 \\ 1 & 3 & 4 \\ 1 & 5 & 6 \end{bmatrix},\quad y = \begin{bmatrix} 2 \\ 7 \\ 10 \end{bmatrix},\quad \theta = \begin{bmatrix} 0 \\ 1 \\ 1 \end{bmatrix} \]
📘 Compute \( \nabla J(\theta) \) step-by-step

Step 1: Predictions \( \hat{y} = X\theta \):

\[ \hat{y} = \begin{bmatrix} 0+1+2 \\ 0+3+4 \\ 0+5+6 \end{bmatrix} = \begin{bmatrix} 3 \\ 7 \\ 11 \end{bmatrix} \]

Step 2: Residual \( \hat{y} - y \):

\[ \hat{y} - y = \begin{bmatrix} 3-2 \\ 7-7 \\ 11-10 \end{bmatrix} = \begin{bmatrix} +1 \\ 0 \\ +1 \end{bmatrix} \]

Step 3: \( X^T (\hat{y} - y) \) (pre-factor):

\[ X^T (\hat{y}-y) = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 3 & 5 \\ 2 & 4 & 6 \end{bmatrix} \begin{bmatrix} 1 \\ 0 \\ 1 \end{bmatrix} = \begin{bmatrix} 1+0+1 \\ 1+0+5 \\ 2+0+6 \end{bmatrix} = \begin{bmatrix} 2 \\ 6 \\ 8 \end{bmatrix} \]

Step 4: Divide by \( m = 3 \):

\[ \nabla J(\theta) = \frac{1}{3} \begin{bmatrix} 2 \\ 6 \\ 8 \end{bmatrix} = \begin{bmatrix} \mathbf{2/3} \\ \mathbf{2} \\ \mathbf{8/3} \end{bmatrix} \]

Problem 2: Feature Scaling Effect

Two features predicting house price: size in sq ft (\( x_1 \in [500, 5000] \)) and bedrooms (\( x_2 \in [1, 5] \)). A GD step updates: \( \theta_1 := \theta_1 - \alpha \cdot 4000 \), \( \theta_2 := \theta_2 - \alpha \cdot 0.1 \).

📘 Diagnose + Fix (Standardization)

Diagnosis: The gradient for \( \theta_1 \) is 40,000× larger than for \( \theta_2 \), so \( \theta_1 \) moves drastically while \( \theta_2 \) creeps. A single α cannot serve both well.


Fix — Standardize both features:

\[ z = \frac{x - \mu}{\sigma} \]

After standardization, \( \mu = 0 \) and \( \sigma = 1 \) for both features. Now both gradients are on the same scale and a single well-chosen α works for all parameters.

Problem 3: Correlation + p-value Combined Reasoning

Feature A: Pearson r = +0.02 with target, p-value = 0.01 after regression.
Feature B: Pearson r = +0.55 with target, p-value = 0.20 after regression.

📘 Step-by-Step Interpretation

Step 1: Feature A (r = 0.02, p = 0.01)

  • Marginal correlation with target is tiny → a correlation filter would drop it.
  • But in the multi-variate model, its coefficient is statistically significant (p < 0.05).
  • Interpretation: A has little univariate linear relation but helps prediction conditional on the other features (suppression / interaction effect). Keep A.

Step 2: Feature B (r = 0.55, p = 0.20)

  • Univariate correlation is strong → a correlation filter would keep it.
  • But in the full model, its coefficient is not statistically significant.
  • Likely cause: B is highly correlated with another feature already in the model (multicollinearity). The model doesn't "need" both. Consider removing B or the collinear partner (use cross-validated performance to decide).

Takeaway: Correlation and p-values answer different questions. Use both, not either one in isolation.

5. Try It Yourself

Problem 1 — One GD Step with α

From Problem 1 above, you found \( \nabla J(\theta) = [2/3,\ 2,\ 8/3]^T \). Starting \( \theta = [0, 1, 1]^T \), apply one gradient-descent step with \( \alpha = 0.1 \). Give the updated \( \theta \).

\begin{align} \theta_0 &:= 0 - 0.1(2/3) = \mathbf{-0.0667} \\ \theta_1 &:= 1 - 0.1(2) = \mathbf{0.8} \\ \theta_2 &:= 1 - 0.1(8/3) = \mathbf{0.7333} \end{align}
Problem 2 — Feature Selection Family Matching

Match each description to the correct family: (F) Filter, (W) Wrapper, (E) Embedded.

  1. "I run my Random Forest once and inspect feature_importances_ to drop unimportant features."
  2. "I rank all features by ANOVA F-value vs. the target, then keep the top 20."
  3. "I start with 0 features, keep adding the feature that most improves CV score, and stop when the score plateaus."
  4. "I fit a linear regression and drop all features with p > 0.05."
  1. (E) Embedded — selection is a byproduct of the RF training.
  2. (F) Filter — statistical scoring before any model is trained.
  3. (W) Wrapper (Forward Selection) — re-trains the model many times searching subsets.
  4. (E) Embedded — uses statistics computed during / after the regression fit.
Problem 3 — Stopping Criteria for GD

A training run plots J(θ) vs. epoch. For each scenario, suggest which stopping strategy (or strategies) from Section 2.7 would be most appropriate and why.

  1. J decreases fast for 100 epochs, then plateaus very close to zero and wiggles by less than 10⁻⁸ each epoch.
  2. Training J keeps decreasing, but validation J started increasing after epoch 30.
  3. You have a tight 2-minute AWS budget and must produce a model; convergence quality is secondary.
  1. Cost-change threshold (ε ≈ 10⁻⁷) OR gradient magnitude. The model has essentially converged; continuing wastes CPU.
  2. Early stopping via validation performance. You're overfitting! Restore the weights from epoch 30 — this is the #1 regularizer for iterative models.
  3. Fixed iterations / wall-clock limit. Run for a budgeted number of epochs and accept the (possibly suboptimal) result.

6. Interactive Quiz

Your score: 0 / 5

7. Key Takeaways

  1. Vectorized GD: \( \nabla J = \frac{1}{m} X^T(X\theta - y) \), update \( \theta := \theta - \alpha \nabla J \). Always confirm matrix dimensions match before coding.
  2. α rules everything: Too small → glacially slow; too large → divergence. The #1 debug step when GD misbehaves is: plot J(θ) vs. epoch.
  3. Feature scaling is not optional for GD: Standardize (z-score) or min-max scale all numeric features. Otherwise the cost bowl is elongated and GD zig-zags.
  4. Stopping strategies: Cost threshold, fixed epochs, validation-loss early stopping, or gradient norm. Early stopping is the most practically useful.
  5. Correlation filter (regression): Pearson r ∈ [−1, +1], drop features with |r| below threshold. Only captures LINEAR relations — non-linear signals may be missed.
  6. p-value embedded selection: p < 0.05 ⇒ keep; p > 0.05 ⇒ consider removal. Remember: high p is not proof of zero effect, only insufficient evidence of non-zero effect.

8. Common Pitfalls

  1. Forgetting to standardize before gradient descent. A feature measured in micrometers and another in kilometers will make α tuning impossible. The fix is always to z-score (or min-max scale) numeric features first.
  2. Misinterpreting "p > 0.05" as proof of irrelevance. Failure to reject H₀ ≠ accepting H₀. The sample might be too small, or the effect weak but real. Use domain knowledge + cross-validation.
  3. Dropping a feature just because its |r| with target is low. A feature with tiny univariate correlation can still be highly useful in the multi-variate model (e.g., suppression effects). Correlation filter is a quick first pass, not a final verdict.
  4. Using a fixed 500 epochs with no monitoring. Either the model hasn't converged (wasteful later epochs do nothing useful) or it overfitted long ago. Always track J and use an intelligent stopper.
  5. Updating parameters one-by-one with freshly computed gradients. Within a single iteration, all gradients must be evaluated on the same θ snapshot and only then applied simultaneously. Piecemeal updates are a common bug.
  6. Confusing Filter vs. Wrapper vs. Embedded families. Filter: before training (fast, model-agnostic). Wrapper: repeated training (slow, model-specific, best subsets). Embedded: during training (middle ground). Pick the right tool for your data budget.

9. Resources